const { 
  getWorker, 
  getWorkerCount, 
  addWorker, 
  updateWorker, 
  deleteWorker, 
  getWorkerListSortFinish,
  getWorkerListSortBenefit
} = require('../service/worker.service');
const { judgeIfMissParam } = require('../utils/common');

class WorkerController {
  // 获取员工数据列表
  async getWorker(ctx, next) {
    const { name, identify, repairType, page, size } = ctx.query;
    // 判断是否缺少参数
    const requireArr = ['name', 'identify', 'repairType'];
    const flag = judgeIfMissParam(ctx, '[worker.controller_getWorker]', requireArr, ctx.query);
    if (!flag) return;

    const result = await getWorker(name, identify, repairType, page, size);
    const totalResult = await getWorkerCount();

    ctx.body = {
      ret: 0,
      data: {
        list: result,
        total: totalResult.total,
        page,
        size,
      }
    }
  }

  // 添加员工数据
  async addWorker(ctx, next) {
    try {
      const arg = ctx.request.body;
      const requiredParam = ['name', 'age', 'phone', 'bornFrom', 'workTime', 'repairType'];
      const flag = judgeIfMissParam(ctx, '[worker.controller_addWorker]', requiredParam, arg);
      if (!flag) return;

      const formData = {
        ...arg,
        identify: 'MR' + new Date().getTime(),
        benefit: 0,
        finish: 0,
        valid: 1,
      }
      const result = await addWorker(formData);
      if (!result) return;
      ctx.body = {
        ret: 0,
        data: 'ok'
      }
    }catch (e) {
      console.log('[worker.controller_addWorker]获取添加员工信息', result);
    }
  }

  // 编辑员工信息
  async updateWorker(ctx, next) {
    try {
      const requireArr = ['id', 'age', 'phone', 'bornFrom'];
      const flag = judgeIfMissParam(ctx, '[worker.controller_updateWorker]', requireArr, ctx.request.body);
      if (!flag) return;
      const result = await updateWorker(ctx.request.body);
      if (!result) return;
      ctx.body = {
        ret: 0,
        data: 'ok'
      }
    } catch (e) {
      console.log('[worker.controller_updateWorker]编辑员工信息', e);
    }
  }

  // 失效员工接口
  async deleteWorker(ctx, next) {
    try {
      const requireArr = ['id'];
      const flag = judgeIfMissParam(ctx, '[worker.controller_deleteWorker]', requireArr, ctx.query);
      if (!flag) return;

      const result = await deleteWorker(ctx.query);
      if (!result) return;
      ctx.body = {
        ret: 0,
        data: 'ok'
      }
    } catch(e) {
      console.log('[worker.controller_deleteWorker]{fail}', e);
    }
  }

  // 获取员工按照订单完成量排序的数据列表(前10位)
  async getWorkerListSortFinish(ctx, next) {
    const result = await getWorkerListSortFinish();
    ctx.body = {
      ret: 0,
      data: {
        list: result
      }
    }
  }

  // 获取员工按照盈利金额排序的数据列表(前10位)
  async getWorkerListSortBenefit(ctx, next) {
    const result = await getWorkerListSortBenefit();
    ctx.body = {
      ret: 0,
      data: {
        list: result
      }
    }
  }
}

module.exports = new WorkerController();